#!/usr/bin/env python3
# coding:utf-8

""" 功能说明
根据磁盘使用率, 动态删除不同时期的日志
磁盘占用50%, 删除3天前的日志
磁盘占用70%, 删除2天前的日志
磁盘占用80%, 删除1天前的日志
磁盘占用85%, 删除12小时前的日志
磁盘占用90%, 删除6小时前的日志
磁盘占用95%, 删除3小时前的日志

"""
import os
import time
import psutil
from dataclasses import dataclass, field
from typing import List

# import debugpy
# debugpy.listen(6688)
# debugpy.wait_for_client()


@dataclass
class Monitor_Policy:
    disk_percent: float = 0
    timeout: int = 0


@dataclass
class Monitor_Rules:
    monitor_disk: str
    monitor_dir: str
    policy: List[Monitor_Policy] = field(default_factory=dict)


rescan_time = 60 * 60
develop_phase_config = [
    Monitor_Rules(
        monitor_disk="/mount_point",    # 自定义监控磁盘 挂载点
        monitor_dir="/var/log",         # 需要监控,清理的 日志,缓存文件目录
        policy=[
            Monitor_Policy(50, 60 * 60 * 24 * 3),
            Monitor_Policy(70, 60 * 60 * 24 * 2),
            Monitor_Policy(80, 60 * 60 * 24 * 1),
            Monitor_Policy(85, 60 * 60 * 12),
            Monitor_Policy(90, 60 * 60 * 6),
            Monitor_Policy(95, 60 * 60 * 3),
            # Monitor_Policy(98, 60 * 60 * 2),
        ],
    ),
]

release_phase_config = [
    Monitor_Rules(
        monitor_disk="/mount_point",
        monitor_dir="/var/log",
        policy=[
            Monitor_Policy(50, 60 * 60 * 24 * 7),
            Monitor_Policy(70, 60 * 60 * 24 * 5),
            Monitor_Policy(80, 60 * 60 * 24 * 3),
            Monitor_Policy(85, 60 * 60 * 24 * 1),
            Monitor_Policy(90, 60 * 60 * 12),
            Monitor_Policy(95, 60 * 60 * 6),
        ],
    ),
]


class Monitor_Service:
    def __init__(self, config, rescan_time):
        self.config = config
        self.rescan_time = rescan_time

    def delete_old_files_and_dirs(self, path, timeout_time):
        current_time = time.time()
        try:
            for entry in os.scandir(path):
                entry_mtime = entry.stat().st_mtime
                # 计算时间差（以秒为单位）
                time_diff = current_time - entry_mtime

                if entry.is_file():
                    if time_diff > timeout_time:
                        os.remove(entry.path)
                elif entry.is_dir():
                    # 如果是目录，递归调用函数处理子目录
                    self.delete_old_files_and_dirs(entry.path, timeout_time)
                    if not os.listdir(entry.path) and time_diff > timeout_time:
                        # print(f"Deleting directory: {entry.path}")
                        os.rmdir(entry.path)

        except Exception as e:
            print(f"Error processing {path}: {e}")

    def monitor_and_clean_log(self):
        for rule in self.config:
            mount_point = rule.monitor_disk
            for item_policy in rule.policy:
                disk_info = psutil.disk_usage(mount_point)
                if disk_info.percent >= item_policy.disk_percent:
                    self.delete_old_files_and_dirs(rule.monitor_dir, item_policy.timeout)
                else:
                    break

    def loop_run(self):
        while True:
            self.monitor_and_clean_log()
            time.sleep(self.rescan_time)


def main():
    monitor = Monitor_Service(develop_phase_config, rescan_time)
    # monitor.loop_run()
    monitor.monitor_and_clean_log()


if __name__ == "__main__":
    main()
